import 'package:bordered_text/bordered_text.dart';
import 'package:flutter/widgets.dart';
import 'package:lottie/lottie.dart';
import '../../public.dart';
import 'events/_index.dart';
import 'mixins/widget_base.dart';

/// 用户福利圆圈
class ReaderUserBenefits extends StatefulWidget {
  ReaderUserBenefits({Key key}) : super(key: key);

  @override
  ReaderUserBenefitsState createState() => new ReaderUserBenefitsState();
}

class ReaderUserBenefitsState extends State<ReaderUserBenefits>
    with ReaderWidgetBase, TickerProviderStateMixin {
  AnimationController circleController; // 圆圈
  AnimationController pigController; // 小猪
  AnimationController textController; // 文本
  Animation<Offset> textAnimation; // 文本
  var sub; // 章节序号改变
  var subScroll; // 滑动事件

  double pX = 16; // 圆圈位置offsetX
  double pY = 333; // 圆圈位置offsetY
  double circleWidth = 54; // 圆圈大小
  double val = 0; // 圆圈进度
  bool doAnimation = false; // 是否执行动画
  bool doNum = false; // 是否执行数字动画
  bool doPig = false; // 是否执行小猪整体动画(临时逻辑，后面换成时间阅读逻辑)
  bool showBenefits = false; // 是否显示小猪(滚动头部300距离显示)

  @override
  void initState() {
    super.initState();

    initEvent();
    initAnimation();
  }

  @override
  void dispose() {
    circleController.dispose();
    pigController.dispose();
    textController.dispose();

    sub.cancel();
    subScroll.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (!showBenefits) {
      return SizedBox.shrink();
    }
    return Positioned(left: pX, top: pY, child: _body());
  }

  initEvent() {
    sub =
        readerPage.bus.on<ReaderChapterImageIndexChangeEvent>().listen((event) {
      val = readModel.currentImageIndex / readModel.currentChapter.totalPage;
      circleController.forward();
      if (val > 0.6 && !doPig) {
        doAnimation = true;
        doPig = true;
        pigController.forward();
      }
    });

    subScroll = readerPage.bus.on<ReaderMoveEvent>().listen((event) {
      var re = event.offset > 100;
      if ((re && !showBenefits) || !re && showBenefits) {
        showBenefits = re;
        setState(() {});
      }
    });
  }

  initAnimation() {
    /// 圆圈
    circleController = AnimationController(
      vsync: this,
      duration: Duration(seconds: 10),
    );
    circleController.addListener(() {
      if (circleController.value > val) {
        circleController.stop();
      }
      if (circleController.status == AnimationStatus.completed) {
        doPig = false;
        circleController.reset();
      }
    });

    /// 猪
    pigController = AnimationController(
        duration: const Duration(milliseconds: 1200), vsync: this);
    pigController.addListener(() {
      if (pigController.value > 0.5 && !doNum) {
        textController.forward();
        doNum = true;
      }
      if (pigController.status == AnimationStatus.completed) {
        doAnimation = false;
        pigController.reset();
      }
    });

    /// 文字
    textController = AnimationController(
        duration: const Duration(milliseconds: 600), vsync: this);
    textAnimation = Tween(begin: Offset(10, 0), end: Offset(10, -20))
        .animate(textController);
    textController.addListener(() {
      if (textController.status == AnimationStatus.completed) {
        doNum = false;
        textController.reset();
      }
    });
  }

  Widget _body() {
    return buildListen(Stack(
      alignment: Alignment.center,
      overflow: Overflow.visible,
      children: [
        SizedBox(
            width: circleWidth,
            height: circleWidth,
            child: AnimatedBuilder(
              animation: circleController,
              builder: (context, child) => buildCircle(),
              child: buildCircle(),
            )),
        Lottie.asset('assets/jsons/pig.json',
            controller: pigController, width: 40, height: 40),
        // ImagesAnimation(
        //     controller: pigController,
        //     w: 40,
        //     h: 40,
        //     entry: ImagesAnimationEntry(
        //         0, 11, AppConfig.ASSETS_PATH + "read_pig/%s.png")),
        buildText()
      ],
    ));
  }

  buildCircle() {
    return Container(
        decoration: BoxDecoration(
            color: ColorUtil.rgba(0, 0, 0, 0.2), shape: BoxShape.circle),
        child: CircularProgressIndicator(
          value: circleController.value,
          strokeWidth: 2,
          valueColor: AlwaysStoppedAnimation(ColorUtil.rgba(255, 213, 50, 1)),
        ));
  }

  Widget buildListen(Widget widget) {
    return Listener(onPointerMove: onPointerMove, child: widget);
  }

  /// 拖动中
  void onPointerMove(PointerMoveEvent pointerMoveEvent) {
    pY = pointerMoveEvent.position.dy - circleWidth / 2;
    pX = pointerMoveEvent.position.dx - circleWidth / 2;
    if (pY + circleWidth > readModel.screenHeight) {
      pY = readModel.screenHeight - circleWidth;
    }
    if (pY < 0) {
      pY = 0;
    }
    if (pX + circleWidth > readModel.screenWidth) {
      pX = readModel.screenWidth - circleWidth;
    }
    if (pX < 0) {
      pX = 0;
    }
    readerMainPage.doKeepPage();
    setState(() {});
  }

  textWidget() {
    if (!doAnimation) {
      return Container();
    }
    return BorderedText(
      strokeColor: Colors.white,
      strokeWidth: 2,
      child: Text(
        '+33',
        style: TextStyle(color: Colors.red, fontSize: 14),
      ),
    );
  }

  buildText() {
    return AnimatedBuilder(
        animation: textAnimation,
        builder: (context, child) => Transform.translate(
            offset: textAnimation.value, child: textWidget()),
        child: textWidget());
  }
}
